<script setup>
import { initCollapses } from 'flowbite'
import { onMounted,ref,reactive} from 'vue'
import axios from '../utils/axios';
import { CircleCloseFilled,SuccessFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {useRouter} from 'vue-router'
onMounted(() => {
  if(localStorage.getItem('token')){
    isLogin.value = true
    imgUrl.value = localStorage.getItem('imgUrl')
  }
  initCollapses();
})
let router = useRouter()
let imgUrl = ref('../../public/img/logo.png')
const dialogLogin = ref(false)
let dialogSignIn = ref(false)
let password = ref('')
let isLogin = ref(false)
const formLabelWidth = '25%'
const use = reactive({
  userName: '',
  password: '',
  code: '',
  uuid: '',
  codeUrl: ''
})
const newUse = reactive({
  userName: '',
  password: '',
  phone: '',
  code: '',
  uuid: '',
  codeUrl: ''
})
const newUseTips = reactive({
  userName: '',
  password: '',
  twoPassword: '',
  phone: '',
}) 
const useTips = reactive({
  userName: '',
  password: ''
})
function skipSingIn(){
  dialogLogin.value = false
  dialogSignIn.value = true
}
function skipLogin(){
  dialogSignIn.value = false
  dialogLogin.value = true
  getCodeUrl()
}
async function login(){
  if(!(useTips.userName && useTips.password && use.code)){
    ElMessage({
      message:'输入内容有误',
      type: 'error',
      center: true
    })
  }
  const {data} = await axios.post('login',use,{
    headers:{
      'Content-Type':'application/x-www-form-urlencoded'
    }
  })
  if(data.success){
    localStorage.setItem('token',data.data.token)
    localStorage.setItem('imgUrl',data.data.headPortrait)
    ElMessage({
      message:'登录成功',
      type: 'success',
      center: true,
      duration: 500
    })
    setTimeout(() => {
    imgUrl.value = localStorage.getItem('imgUrl')
    dialogLogin.value = false
    isLogin.value = true
    use.userName = ''
    use.password = ''
    use.code = ''
  },500)
  }
  else{
    ElMessage({
      message:'登录失败',
      type: 'error',
      center: true,
      duration: 1000
    })
  }
}
async function SingIn(){
  if(!(newUseTips.userName && newUseTips.password && newUseTips.twoPassword && newUseTips.phone && newUse.code)){
    ElMessage({
      message:'输入内容有误',
      type: 'error',
      center: true,
      duration: 1000
    })
    return
  }
  const {data} = await axios.post('register',newUse,{
    headers:{
      'Content-Type':'application/x-www-form-urlencoded'
    }
  })
  if(data.success){
    ElMessage({
      message:'注册成功',
      type: 'success',
      center: true,
      duration: 500
    })
    setTimeout(() => {
    dialogSignIn.value = false
    dialogLogin.value = true
    use.userName = ''
    use.password = ''
    use.code = ''
  },500)
  }
  else{
    ElMessage({
      message:'注册失败',
      type: 'error',
      center: true,
      duration: 1000
    })
  }
  
}
async function checkUserName(name,id){
  let usernameReg=/^[a-zA-Z0-9]{2,10}$/
  if(!usernameReg.test(name)){
    if(id === '0') useTips.userName = false
    else newUseTips.userName = false
    return
  }
  const {data} = await axios.get(`isOne?userName=${newUse.userName}`)
  if(!data.success){
    ElMessage({
      message:'用户名不唯一',
      type: 'error',
      center: true,
      duration: 5000
    })
    setTimeout(() => {
      newUse.userName = ''
      newUseTips.userName = false
      return
    },500)
  }
  if(id === '0') useTips.userName = true
  else newUseTips.userName = true
}
function checkPassword(password,id){
  let passwordReg=/^[a-zA-Z0-9]{5,10}$/
  if(!passwordReg.test(password)){
    if(id === '0') useTips.password = false
    else newUseTips.password = false
    return
  }
  if(id === '0') useTips.password = true
  else newUseTips.password = true
}
function checkTowPassword(){
  if(!newUse.password === password.value) newUseTips.twoPassword = false
  else newUseTips.twoPassword = true
}
function checkPhone(){
  let phoneReg = /^[0-9]{11}$/
  if(!phoneReg.test(newUse.phone)) newUseTips.phone = false
  else newUseTips.phone = true
}
async function getCodeUrl(key){
  if(key){
    const {data} = await axios.get(`getcode?uuid=${use.uuid}`)
    use.uuid= data.data.uuid
    use.codeUrl = data.data.url
  }
  else{
    const {data} = await axios.get(`getcode?uuid=${newUse.uuid}`)
    newUse.uuid= data.data.uuid
    newUse.codeUrl = data.data.url
  }
}
function openLogin(){
  dialogLogin.value = true
  getCodeUrl(true)
}
function checkToken(){
  if(!localStorage.getItem('token')){
    router.push({path:'/home'})
    openLogin()
  }
}
function openSingIn(){
  dialogSignIn.value = true
  getCodeUrl(false)
}
function logout(){
  isLogin.value = !isLogin.value
  localStorage.removeItem('token')
  localStorage.removeItem('imgUrl')
  imgUrl.value = '../../public/img/logo.png'
  router.push({path:'/home'})
}
</script>

<template>
  <div>
    <nav class="dark:bg-gray-900 fixed w-full z-20 top-0 start-0 border-b border-gray-200 dark:border-gray-600" style="background-color: #CDD0D6;">
      <div class="max-w-screen-xl flex flex-wrap items-center justify-between mx-auto p-4">
      <a href="https://flowbite.com/" class="flex items-center space-x-3 rtl:space-x-reverse">
          <img src="../../public/img/logo.png" class="h-12" alt="CatAndDog Logo" />
          <span class="self-center text-2xl font-semibold whitespace-nowrap dark:text-white">CatAndDog</span>
      </a>
      <div class="flex md:order-2 space-x-3 md:space-x-0 rtl:space-x-reverse">
          <router-link to="/personal" @click="checkToken()"><el-avatar :size="40" :src="imgUrl" /></router-link>
          &nbsp;
          <div v-if="!isLogin">
            <button type="button" @click="openLogin(true)" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-4 py-2 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">登录</button>
            &nbsp;
            <button type="button" @click="openSingIn(false)" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-4 py-2 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">注册</button>
          </div>
          <button v-else type="button" @click="logout()" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-4 py-2 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">退出登录</button>
      </div>
      <div class="items-center justify-between hidden w-full md:flex md:w-auto md:order-1" id="navbar-cta">
        <ul class="flex flex-col font-medium p-4 md:p-0 mt-4 border border-gray-100 rounded-lg bg-gray-50 md:space-x-8 rtl:space-x-reverse md:flex-row md:mt-0 md:border-0 md:bg-white dark:bg-gray-800 md:dark:bg-gray-900 dark:border-gray-700" style="background-color: #CDD0D6;">
          <li >
            <router-link to="/home" class="block py-2 px-3 md:p-0 text-gray-900 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-700 md:dark:hover:text-blue-500 dark:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">
              首页
            </router-link>
          </li>
          <li>
            <router-link to="/animal" @click="checkToken()" class="block py-2 px-3 md:p-0 text-gray-900 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-700 md:dark:hover:text-blue-500 dark:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700" >
              萌宠
            </router-link>
          </li>
          <li>
            <router-link to="/dynamicState" @click="checkToken()"  class="block py-2 px-3 md:p-0 text-gray-900 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-700 d:dark:hover:text-blue-500 dark:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">
              萌宠圈
            </router-link>
          </li>
          <li>
            <router-link to="/commonSense" @click="checkToken()"  class="block py-2 px-3 md:p-0 text-gray-900 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-700 md:dark:hover:text-blue-500 dark:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">
              小常识
            </router-link>
          </li>
          <li>
            <router-link to="/personal" @click="checkToken()"  id="page5" class="block py-2 px-3 md:p-0 text-gray-900 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-700 md:dark:hover:text-blue-500 dark:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">
              个人中心
            </router-link>
          </li>
        </ul>
      </div>
      </div>
    </nav>
    <!--登录-->
    <div style="margin: auto;">
      <el-dialog v-model="dialogLogin" title="CatAndDog LOGIN" width="500" style="text-align: center;">
        <el-form>
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input v-model="use.userName" autocomplete="off" @blur="checkUserName(use.userName,'0')" style="width: 90%;"/>
            <div style="margin-top: -32px;margin-left: 93%;">
              <el-icon v-if="useTips.userName" color="green"><SuccessFilled /></el-icon>
              <el-icon v-else  color="red"><CircleCloseFilled /></el-icon>
            </div>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth">
            <el-input v-model="use.password" autocomplete="off" show-password @blur="checkPassword(use.password,'0')" style="width: 90%;"/>
            <div style="margin-top: -32px;margin-left: 93%;">
              <el-icon v-if="useTips.password" color="green"><SuccessFilled /></el-icon>
              <el-icon v-else  color="red"><CircleCloseFilled /></el-icon>
            </div>
          </el-form-item>
          <el-form-item label="验证码" :label-width="formLabelWidth" >
            <el-input v-model="use.code" autocomplete="off" style="width: 70%;" />
            &nbsp;&nbsp;&nbsp;
            <img :src="use.codeUrl" alt="" style="width: 25%;" @click="getCodeUrl(true)">
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="skipSingIn">
              去注册
            </el-button>
            <el-button type="primary" @click="login">
              登录
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!--注册-->
    <div style="margin: auto;">
      <el-dialog v-model="dialogSignIn" title="CatAndDog SingIn" width="500" style="text-align: center;">
        <el-form>
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input v-model="newUse.userName" autocomplete="off" @blur="checkUserName(newUse.userName,'1')" style="width: 90%;"/>
            <div style="margin-top: -32px;margin-left: 93%;">
              <el-icon v-if="newUseTips.userName" color="green"><SuccessFilled /></el-icon>
              <el-icon v-else  color="red"><CircleCloseFilled /></el-icon>
            </div>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth">
            <el-input v-model="newUse.password" autocomplete="off" show-password @blur="checkPassword(newUse.password,'1')" style="width: 90%;"/>
            <div style="margin-top: -32px;margin-left: 93%;">
              <el-icon v-if="newUseTips.password" color="green"><SuccessFilled /></el-icon>
              <el-icon v-else  color="red"><CircleCloseFilled /></el-icon>
            </div>
          </el-form-item>
          <el-form-item label="再次输入密码" :label-width="formLabelWidth" >
            <el-input v-model="password" autocomplete="off" show-password @blur="checkTowPassword" style="width: 90%;" />
            <div style="margin-top: -32px;margin-left: 93%;">
              <el-icon v-if="newUseTips.twoPassword" color="green"><SuccessFilled /></el-icon>
              <el-icon v-else  color="red"><CircleCloseFilled /></el-icon>
            </div>
          </el-form-item>
          <el-form-item label="手机号" :label-width="formLabelWidth">
            <el-input v-model="newUse.phone" autocomplete="off" password @blur="checkPhone" style="width: 90%;"/>
            <div style="margin-top: -32px;margin-left: 93%;">
              <el-icon v-if="newUseTips.phone" color="green"><SuccessFilled /></el-icon>
              <el-icon v-else  color="red"><CircleCloseFilled /></el-icon>
            </div>
          </el-form-item>
          <el-form-item label="验证码" :label-width="formLabelWidth" >
            <el-input v-model="newUse.code" autocomplete="off" style="width: 70%;" />
            &nbsp;&nbsp;&nbsp;
            <img :src="newUse.codeUrl" alt="" style="width: 25%;" @click="getCodeUrl(false)">
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="skipLogin">
              去登录
            </el-button>
            <el-button type="primary" @click="SingIn">
              注册
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
a.router-link-active {
  color: #409EFF;
}
</style>
